package pers.chao.tool.http;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: web常用工具集，获取当前请求的相关信息
 *
 * @author W.Chao
 * @date 2020/11/8 16:15
 **/
public final class WebUtil {

	private static final String[] ipHeaders = {
			"X-Forwarded-For",
			"X-Real-IP",
			"Proxy-Client-IP",
			"WL-Proxy-Client-IP"
	};

	private WebUtil() {
	}

	/**
	 * 获取当前请求的HttpServletRequest实例
	 *
	 * @return
	 */
	public static HttpServletRequest getHttpServletRequest() {
		try {
			ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			return requestAttributes != null ? requestAttributes.getRequest() : null;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取请求参数列表
	 *
	 * @param request
	 * @return
	 */
	public static Map<String, String> getParameters(HttpServletRequest request) {
		Map<String, String> parameters = new HashMap<>();
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String name = parameterNames.nextElement();
			parameters.put(name, request.getParameter(name));
		}
		return parameters;
	}

	/**
	 * 获取请求头参数列表
	 *
	 * @param request
	 * @return
	 */
	public static Map<String, String> getHeaders(HttpServletRequest request) {
		Map<String, String> headers = new HashMap<>();
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String name = headerNames.nextElement();
			headers.put(name, request.getHeader(name));
		}
		return headers;
	}

	/**
	 * 获取请求客户端的真实ip地址
	 *
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		for (String ipHeader : ipHeaders) {
			String ip = request.getHeader(ipHeader);
			if (!StringUtils.isEmpty(ip) && !ip.contains("unknown")) {
				return ip;
			}
		}
		return request.getRemoteAddr();
	}

	/**
	 * web应用绝对路径
	 *
	 * @param request
	 * @return
	 */
	public static String getBasePath(HttpServletRequest request) {
		String path = request.getContextPath();
		return (request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/");
	}
}
